<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Organization;
use app\admin\model\Menu;
use app\admin\model\Organizationjobrule;

use think\Request;

class Organizationjob extends Base
{

    protected $organizationId;

    protected $organization;

    public function _initialize()
    {
        parent::_initialize();

        $organizationId = $this->request->param('organizeid');
        if($organizationId){
            $organization = Organization::where(['id' => $organizationId, 'isDelete' => 2])->field('id, name')->find();

            !$organization && $this->redirect('admin/index/index');

            $this->defaultWhere = [
                'villageId' => $this->admin->villageId,
                'organizationId' => $organizationId,
                'isDelete' => ['neq', 1]
            ];
            $this->defaultOrder = 'sorting ASC';
            $this->organizationId = $organizationId;
            $this->organization = $organization;

            $this->assign('organization', $organization);
        }else{
            $this->redirect('admin/index/index');
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){
        $accessTree = Helper::makeTreeViews(
            \app\admin\model\Menu::class,
            ['id' => ['neq', 1]], // 首页不参与权限控制
            ['sorting' => 'asc', 'id' => 'asc'],
            []
        );
        $this->assign('accessTree', $accessTree);

        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){
        $model = model($this->model);

        //save data
        if ($request->isPost()) {
            $data = $request->param();
            // Insert data
            $data['id'] = Helper::getUUID();
            $data['organizationId'] = $data['organizeid'];
            $data['createDate'] = time();
            $data['updateDate'] = time();
            $data['createOper'] = $this->admin->id;
            $data['updateOper'] = $this->admin->id;
            $data['villageId'] = $this->admin->villageId;

            $result = $model->save($data);

            if($result !== false){
                // 写入日志
                $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                common::adminLog($request, $logInfo);

                $access = $request->param('rules');
                $this->setAccess($data['id'], $access);

                return $this->success('添加成功！', url('admin/organizationjob/index', ['organizeid' => $this->organizationId]));
            }else{
                return $this->error($model->getError());
            }
        } else {
            return $this->error('添加失败');
        }
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $accessTree = Helper::makeTreeViews(
            \app\admin\model\Menu::class,
            ['id' => ['neq', 1], 'status' => ['neq','3']],
            ['sorting' => 'asc', 'id' => 'asc'],
            []
        );
        $this->assign('accessTree', $accessTree);

        $jobId = $request->param('id');
        $rules = Organizationjobrule::where('jobId', $jobId)->field('menuId')->select();
        $access = '';
        foreach ($rules as $item) {
            $access .= ',' . $item['menuId'];
        }
        $this->assign('access', substr($access, 1));

        return parent::edit($request);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){
        $model = model($this->model);

        //save data
        if ($request->isPost()) {
            $data = $request->param();
            // Update data
            $data['updateDate'] = time();
            $data['updateOper'] = $this->admin->id;
            //unset($data['organizeid']);
            //unset($data['rules']);

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if ($result !== false) {
                // 写入日志
                $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                common::adminLog($request, $logInfo);

                $access = $request->param('rules');
                $this->setAccess($data['id'], $access);

                return $this->success('编辑成功！', url('admin/organizationjob/index', ['organizeid' => $this->organizationId]));
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('编辑失败！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if(isset($_POST['ids'])){
            // 删除多条
//            $ids = $request->param('ids');
//
//            $result = $model->whereIn('id', $ids)->update(['isDelete' => 1]);
//
//            if($result !== false) {
//                // 成员&职务 关联
//                $operatorJob = model('Operatorjob');
//                $operatorIds = $operatorJob->whereIn('jobId', $ids)->field('operatorId')->select();
//                $operatorIds = array_column($operatorIds, 'operatorId');
//                $operatorJob->whereIn('jobId', $ids)->update(['isDelete' => 1]);
//                // 成员
//                model('Operator')->whereIn('id', $operatorIds)->update(['isDelete' => 1]);
//
//                $logInfo = $this->admin->name . '删除了' . count($ids) . '条' . $this->model . '数据。';
//                common::adminLog($request, $logInfo);
//            }
        }else if($id){
            //删除一条
            $info = $model->find(['id', $id]);
            if(!$info){
                return redirect('admin/'.$this->model.'/index');
            }

            if($id == $this->admin->jobId){
                return $this->error('您属于当前组织职务，您不能删除！', url('admin/organizationjob/index', ['organizeid' => $this->organizationId]));
            }

            $result = $model->where('id', $id)->update(['isDelete' => 1]);

            if($result !== false) {
                // 成员&职务 关联
                $operatorJob = model('Operatorjob');
                $operatorIds = $operatorJob->where(['jobId' => $id, 'isDelete' => 2])->field('operatorId')->select();
                $operatorIds = array_column($operatorIds, 'operatorId');
                // 成员
                $operator = model('Operator');
                //$operator->whereIn('id', $operatorIds)->update(['isDelete' => 1]);
                foreach($operatorIds as $operatorId){
                    // 是否有多个职位
                    $jobCount = $operatorJob->where(['operatorId' => $operatorId, 'isDelete' => 2])->count();
                    if($jobCount == 1){
                        $operator->where('id', $operatorId)->update(['isDelete' => 1]);
                    }
                }
                $operatorJob->where(['jobId' => $id, 'isDelete' => 2])->update(['isDelete' => 1]);

                $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                common::adminLog($request, $logInfo);
            }
        }

        if($result !== false){
            return $this->success('删除成功！', url('admin/organizationjob/index', ['organizeid' => $this->organizationId]));
        }else{
            return $this->error('删除失败！', url('admin/organizationjob/index', ['organizeid' => $this->organizationId]));
        }
    }

    /**
     * 设置权限
     *
     * @param int $jobId 职务ID
     * @param string $access 权限
     * @return bool
     */
    public function setAccess($jobId, $access){
        $accessArr = explode(',', $access);
        if(!empty($accessArr)){
            $data = [];
            $model = model('Organizationjobrule');
            $model->where('jobId', $jobId)->delete();
            foreach ($accessArr as $item) {
                $data['jobId'] = $jobId;
                $data['menuId'] = $item;

                $model->create($data);
            }
        }

        return true;
    }

}